package com.module.ble.utils

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat
import com.common.base.app.extras.getContext

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：13/5/2025
 *
 * 描述：蓝牙配对状态并进行蓝牙配对
 *
 * 修订历史：
 *
 */
object BluetoothPairingUtil {

    private var bluetoothStateReceiver: BroadcastReceiver? = null
    private var isBluetoothStateListening = false

    private val bluetoothAdapter: BluetoothAdapter? by lazy {
        (getContext().getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)?.adapter
    }

    private fun hasBluetoothPermissions(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED
        }
    }

    //检查特定设备是否已配对
    @RequiresPermission(allOf = ["android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"])
    fun isDevicePaired(macAddress: String): Boolean {
        Log.i("BluetoothPairingUtil", "SO=====isDevicePaired")
        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
            return false
        }
        Log.i("BluetoothPairingUtil", "SO=====isDevicePaired2")

        return try {
            // 创建本地变量以解决智能类型转换问题
            val adapter = bluetoothAdapter ?: return false
            adapter.bondedDevices.any { device ->
                device.address == macAddress
            }
        } catch (e: SecurityException) {
            // 处理权限被拒绝的情况
            e.printStackTrace()
            false
        }
    }

    @Synchronized
    @RequiresPermission(allOf = ["android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"])
    fun pairDevice(macAddress: String?, callback: (Boolean) -> Unit) {
        Log.i("BluetoothPairingUtil", "SO=====pairDevice")
        if (macAddress.isNullOrEmpty()) {
            callback(false)
            return
        }
        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
            callback(false)
            return
        }

        try {
            // 创建本地变量以解决智能类型转换问题
            val adapter = bluetoothAdapter ?: run {
                callback(false)
                return
            }

            val device = adapter.getRemoteDevice(macAddress)

            if (device.bondState == BluetoothDevice.BOND_BONDED) {
                callback(true)
                return
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                device.createBond()
                callback(true)
            } else {
                val pairMethod = device.javaClass.getMethod("createBond")
                pairMethod.invoke(device)
                callback(true)
            }
        } catch (e: SecurityException) {
            // 处理权限被拒绝的情况
            e.printStackTrace()
            callback(false)
        } catch (e: Exception) {
            e.printStackTrace()
            callback(false)
        }
    }

    @RequiresPermission(allOf = ["android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"])
    fun pairDeviceNew(macAddress: String?, callback: (Boolean) -> Unit) {
        Log.i("BluetoothPairingUtil", "SO=====pairDeviceNew")
        if (macAddress.isNullOrEmpty()) {
            callback(false)
            return
        }

        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
            callback(false)
            return
        }

        try {
            // 创建本地变量以解决智能类型转换问题
            val adapter = bluetoothAdapter ?: run {
                callback(false)
                return
            }

            val device = adapter.getRemoteDevice(macAddress)

            if (device.bondState == BluetoothDevice.BOND_BONDED) {
                callback(true)
                return
            }

            // 注册广播接收器监听配对状态变化
            val pairingReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    val action = intent.action
                    if (BluetoothDevice.ACTION_BOND_STATE_CHANGED == action) {
                        val bondDevice = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
                        } else {
                            @Suppress("DEPRECATION")
                            intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                        }

                        if (bondDevice?.address == macAddress) {
                            val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
                            if (bondState == BluetoothDevice.BOND_BONDED) {
                                Log.i("SOSOU---BluetoothPairingUtil", "SO=====配对成功")
                                // 配对成功
                                context.unregisterReceiver(this)
                                callback(true)
                            } else if (bondState == BluetoothDevice.BOND_NONE) {
                                // 配对失败或被取消
                                Log.i("SOSOU---BluetoothPairingUtil", "SO=====配对失败或被取消")
                                context.unregisterReceiver(this)
                                callback(false)
                            }
                        }
                    }
                }
            }

            // 注册广播接收器
            val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
            // 添加配对请求广播监听
            filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
            getContext().registerReceiver(pairingReceiver, filter)

            // 开始配对
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                device.createBond()
            } else {
                val pairMethod = device.javaClass.getMethod("createBond")
                pairMethod.invoke(device)
            }

            // 不要立即调用callback，等待广播接收器接收到配对结果后再调用
        } catch (e: SecurityException) {
            // 处理权限被拒绝的情况
            e.printStackTrace()
            callback(false)
        } catch (e: Exception) {
            e.printStackTrace()
            callback(false)
        }
    }

    /**
     * 删除配对
     */
    @SuppressLint("MissingPermission")
    fun unpairBluetoothDevice(macAddress: String): Boolean {
        // 检查蓝牙权限
        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
            return false
        }

        if (bluetoothAdapter == null || bluetoothAdapter?.isEnabled != true) {
            return false
        }
        if(macAddress.isNullOrEmpty()) return false

        bluetoothAdapter?.let {
            try {
                val device = it.getRemoteDevice(macAddress)

                // 检查设备是否已配对
                if (device.bondState != BluetoothDevice.BOND_BONDED) {
                    Log.w("SOSOU---Bluetooth", "Device is not paired")
                    return false
                }

                // 使用反射调用removeBond方法
                val removeBondMethod = device.javaClass.getMethod("removeBond")
                val result = removeBondMethod.invoke(device) as Boolean

                if (result) {
                    Log.i("SOSOU---Bluetooth", "Device unpaired successfully")
                } else {
                    Log.e("SOSOU---Bluetooth", "Failed to unpair device")
                }

                return result

            } catch (e: Exception) {
                Log.e("SOSOU---Bluetooth", "Error unpairing device: ${e.message}", e)
                return false
            }
        }
        return false
    }

//    @RequiresPermission(allOf = ["android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN"])
//    fun unpairBluetoothDevice(macAddress: String): Boolean {
//
//        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
//            return false
//        }
//        bluetoothAdapter?.let {
//            try {
//                val device = it.getRemoteDevice(macAddress)
//                if (device.bondState == BluetoothDevice.BOND_BONDED) {
//                    // 使用反射调用隐藏的removeBond方法
//                    val method = device.javaClass.getMethod("removeBond")
//                    return method.invoke(device) as Boolean
//                }
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//        }
//        return false
//    }

    /**
     * 无感建立配对（自动配对）
     * @param macAddress 设备MAC地址
     * @param pin 配对PIN码（可选，某些设备需要）
     * @param callback 配对结果回调
     */
    @SuppressLint("MissingPermission")
    fun pairDeviceSilently(macAddress: String?, pin: String? = null, callback: (Boolean) -> Unit) {
        if (macAddress.isNullOrEmpty()) {
            callback(false)
            return
        }

        if (bluetoothAdapter == null || !hasBluetoothPermissions()) {
            callback(false)
            return
        }

        try {
            val adapter = bluetoothAdapter ?: run {
                callback(false)
                return
            }

            val device = adapter.getRemoteDevice(macAddress)

            if (device.bondState == BluetoothDevice.BOND_BONDED) {
                callback(true)
                return
            }

            // 注册配对请求广播接收器
            val silentPairingReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context, intent: Intent) {
                    when (intent.action) {
                        BluetoothDevice.ACTION_PAIRING_REQUEST -> {
                            val pairingDevice = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
                            } else {
                                @Suppress("DEPRECATION")
                                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                            }

                            if (pairingDevice?.address == macAddress) {
                                try {
                                    // 获取配对类型
                                    val pairingVariant = intent.getIntExtra(
                                        BluetoothDevice.EXTRA_PAIRING_VARIANT,
                                        BluetoothDevice.ERROR
                                    )

                                    when (pairingVariant) {
                                        BluetoothDevice.PAIRING_VARIANT_PIN -> {
                                            // PIN码配对
                                            if (!pin.isNullOrEmpty()) {
                                                val setPinMethod = pairingDevice.javaClass.getMethod("setPin", ByteArray::class.java)
                                                setPinMethod.invoke(pairingDevice, pin.toByteArray())
                                            }
                                        }
                                        BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION -> {
                                            // 密钥确认配对
                                            val setPairingConfirmationMethod = pairingDevice.javaClass.getMethod(
                                                "setPairingConfirmation",
                                                Boolean::class.javaPrimitiveType
                                            )
                                            setPairingConfirmationMethod.invoke(pairingDevice, true)
                                        }
//                                        BluetoothDevice.PAIRING_VARIANT_PASSKEY -> {
//                                            // 数字密钥配对
//                                            val pairingKey = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, -1)
//                                            if (pairingKey != -1) {
//                                                val setPairingConfirmationMethod = pairingDevice.javaClass.getMethod(
//                                                    "setPairingConfirmation",
//                                                    Boolean::class.javaPrimitiveType
//                                                )
//                                                setPairingConfirmationMethod.invoke(pairingDevice, true)
//                                            }
//                                        }
                                        else -> {
                                            // 对于其他类型的配对请求，尝试直接确认
                                            try {
                                                val setPairingConfirmationMethod = pairingDevice.javaClass.getMethod(
                                                    "setPairingConfirmation",
                                                    Boolean::class.javaPrimitiveType
                                                )
                                                setPairingConfirmationMethod.invoke(pairingDevice, true)
                                            } catch (e: Exception) {
                                                Log.w("BluetoothPairingUtil", "setPairingConfirmation failed: ${e.message}")
                                            }
                                        }
                                    }

                                    // 取消用户输入界面（隐藏配对对话框）
                                    try {
                                        val cancelPairingUserInputMethod = pairingDevice.javaClass.getMethod("cancelPairingUserInput")
                                        cancelPairingUserInputMethod.invoke(pairingDevice)
                                    } catch (e: Exception) {
                                        Log.w("BluetoothPairingUtil", "cancelPairingUserInput failed: ${e.message}")
                                    }

                                    Log.i("BluetoothPairingUtil", "Silent pairing request handled for variant: $pairingVariant")

                                } catch (e: Exception) {
                                    Log.e("BluetoothPairingUtil", "Silent pairing failed: ${e.message}", e)
                                }
                            }
                        }

                        BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                            val bondDevice = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java)
                            } else {
                                @Suppress("DEPRECATION")
                                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                            }

                            if (bondDevice?.address == macAddress) {
                                val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
                                when (bondState) {
                                    BluetoothDevice.BOND_BONDED -> {
                                        Log.i("BluetoothPairingUtil", "Silent pairing successful")
                                        context.unregisterReceiver(this)
                                        callback(true)
                                    }
                                    BluetoothDevice.BOND_NONE -> {
                                        Log.i("BluetoothPairingUtil", "Silent pairing failed or cancelled")
                                        context.unregisterReceiver(this)
                                        callback(false)
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 注册广播接收器
            val filter = IntentFilter().apply {
                addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
                addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
                priority = IntentFilter.SYSTEM_HIGH_PRIORITY
            }

            getContext().registerReceiver(silentPairingReceiver, filter)

            // 开始配对
            val success = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                device.createBond()
            } else {
                val pairMethod = device.javaClass.getMethod("createBond")
                pairMethod.invoke(device) as Boolean
            }

            if (!success) {
                getContext().unregisterReceiver(silentPairingReceiver)
                callback(false)
            }

        } catch (e: SecurityException) {
            Log.e("BluetoothPairingUtil", "Permission denied: ${e.message}", e)
            callback(false)
        } catch (e: Exception) {
            Log.e("BluetoothPairingUtil", "Silent pairing error: ${e.message}", e)
            callback(false)
        }
    }

    /**
     * 开始监听蓝牙状态变化（持续监听蓝牙是否已关闭）
     * @param onBluetoothStateChanged 蓝牙状态变化回调，参数为true表示蓝牙开启，false表示蓝牙关闭
     */
    fun startBluetoothStateListener(onBluetoothStateChanged: (Boolean) -> Unit) {
        Log.i("BluetoothPairingUtil", "SO=====startBluetoothStateListener")

        // 如果已经在监听，先停止之前的监听
        if (isBluetoothStateListening) {
            stopBluetoothStateListener()
        }

        bluetoothStateReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val action = intent.action
                if (BluetoothAdapter.ACTION_STATE_CHANGED == action) {
                    val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
                    when (state) {
                        BluetoothAdapter.STATE_OFF -> {
                            Log.i("BluetoothPairingUtil", "SO=====蓝牙已关闭")
                            onBluetoothStateChanged(false)
                        }
                        BluetoothAdapter.STATE_ON -> {
                            Log.i("BluetoothPairingUtil", "SO=====蓝牙已开启")
                            onBluetoothStateChanged(true)
                        }
                        BluetoothAdapter.STATE_TURNING_OFF -> {
                            Log.i("BluetoothPairingUtil", "SO=====蓝牙正在关闭")
                        }
                        BluetoothAdapter.STATE_TURNING_ON -> {
                            Log.i("BluetoothPairingUtil", "SO=====蓝牙正在开启")
                        }
                    }
                }
            }
        }

        try {
            val filter = IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)
            getContext().registerReceiver(bluetoothStateReceiver, filter)
            isBluetoothStateListening = true
            Log.i("BluetoothPairingUtil", "SO=====蓝牙状态监听已启动")

            // 立即回调当前蓝牙状态
            val currentState = bluetoothAdapter?.isEnabled ?: false
            onBluetoothStateChanged(currentState)

        } catch (e: Exception) {
            Log.e("BluetoothPairingUtil", "SO=====启动蓝牙状态监听失败: ${e.message}", e)
            isBluetoothStateListening = false
        }
    }

    /**
     * 停止监听蓝牙状态变化
     */
    fun stopBluetoothStateListener() {
        Log.i("BluetoothPairingUtil", "SO=====stopBluetoothStateListener")

        try {
            bluetoothStateReceiver?.let { receiver ->
                getContext().unregisterReceiver(receiver)
                bluetoothStateReceiver = null
                isBluetoothStateListening = false
                Log.i("BluetoothPairingUtil", "SO=====蓝牙状态监听已停止")
            }
        } catch (e: Exception) {
            Log.e("BluetoothPairingUtil", "SO=====停止蓝牙状态监听失败: ${e.message}", e)
        }
    }

    /**
     * 检查当前是否正在监听蓝牙状态
     * @return true表示正在监听，false表示未监听
     */
    fun isBluetoothStateListening(): Boolean {
        return isBluetoothStateListening
    }

    /**
     * 获取当前蓝牙状态
     * @return true表示蓝牙开启，false表示蓝牙关闭或不可用
     */
    fun getCurrentBluetoothState(): Boolean {
        return bluetoothAdapter?.isEnabled ?: false
    }
}